package com.lzx.reggie.filter

import com.alibaba.fastjson.JSON
import com.lzx.reggie.common.BaseContext
import com.lzx.reggie.common.R
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.util.AntPathMatcher
import java.io.IOException
import javax.servlet.*
import javax.servlet.annotation.WebFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import kotlin.jvm.Throws


@WebFilter(filterName = "loginCheckFilter", urlPatterns = ["/*"])
class LoginCheckFilter : Filter {
    companion object {
        //路径匹配器，支持通配符
        private val PATH_MATCHER = AntPathMatcher()
        private val log: Logger = LoggerFactory.getLogger(LoginCheckFilter::class.java)
    }


    @Throws(IOException::class, ServletException::class)
    override fun doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain) {
        val request = servletRequest as HttpServletRequest
        val response = servletResponse as HttpServletResponse

        //1、获取本次请求的URI
        val requestURI = request.requestURI // /backend/index.html
        log.info("拦截到请求：${requestURI}")

        //定义不需要处理的请求路径
        val urls = arrayOf(
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/common/**",
            "/user/sendMsg",
            "/user/login"
        )


        //2、 判断本次请求是否需要处理 ,如果不需要处理，则直接放行
        if (check(urls, requestURI)) {
            log.info("本次请求${requestURI}不需要处理")
            filterChain.doFilter(request, response)
            return
        }

        //4-1、判断登录状态，如果已登录，则直接放行
        val employeeId = request.session.getAttribute("employee")
        if (employeeId != null) {
            log.info("用户已登录，用户id为：$employeeId")
            employeeId as Long
            BaseContext.currentId = employeeId
            filterChain.doFilter(request, response)
            return
        }

        //4-2、判断登录状态，如果已登录，则直接放行
        val userId = request.session.getAttribute("user")
        if (userId != null) {
            log.info("用户已登录，用户id为：$userId")
            userId as Long
            BaseContext.currentId = userId
            filterChain.doFilter(request, response)
            return
        }
        log.info("用户未登录")
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.writer.write(JSON.toJSONString(R.error("NOTLOGIN")))
        return
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    fun check(urls: Array<String>, requestURI: String): Boolean {
        return urls.any { PATH_MATCHER.match(it, requestURI) }

    }
}